import React, { useReducer, useEffect, useMemo } from 'react';
import { Row, Col, Select, Spin } from 'antd';
import { usePositionTypeList } from '../../hooks';

const reducer = (state, action) => {
    const { type, payload } = action;
    switch (type) {
        case 'init':
            return { ...payload };
        case 'first':
            return { ...state, first: payload, second: undefined };
        case 'second':
            return { ...state, second: payload };
        default:
            throw new Error();
    }
};
const dictOptions = dict =>
    dict &&
    dict.map(item => (
        <Select.Option value={item.positionTypeCode} key={item.positionTypeCode}>
            {item.positionTypeName}
        </Select.Option>
    ));
const PostSelector = ({ onChange, style, value, ...otherProps }) => {
    const [positionTypeLoading, positionTypeList] = usePositionTypeList({});
    const [state, dispatch] = useReducer(reducer, {});
    // 一级职位类别
    const currPostTypeItem = useMemo(() => {
        if (state.first && positionTypeList) {
            return positionTypeList.find(item => item.positionTypeCode === state.first) || {};
        }
        return {};
    }, [state.first, positionTypeList]);
    useEffect(() => {
        dispatch({ type: 'init', payload: value });
    }, [value]);
    useEffect(() => {
        onChange(state);
    }, [state.first, state.second]);

    return (
        <Spin spinning={positionTypeLoading}>
            <Row gutter={20} style={style}>
                <Col span={12}>
                    <Select
                        {...otherProps}
                        allowClear
                        placeholder="请选择"
                        value={state.first}
                        onChange={val => {
                            dispatch({ type: 'first', payload: val });
                        }}
                        getPopupContainer={trigger => trigger.parentElement}
                    >
                        {dictOptions(positionTypeList)}
                    </Select>
                </Col>
                <Col span={12}>
                    <Select
                        {...otherProps}
                        allowClear
                        placeholder="请选择"
                        value={state.second}
                        onChange={val => {
                            dispatch({ type: 'second', payload: val });
                        }}
                        getPopupContainer={trigger => trigger.parentElement}
                    >
                        {dictOptions(currPostTypeItem.children)}
                    </Select>
                </Col>
            </Row>
        </Spin>
    );
};
export default PostSelector;
